<template>
    <div class="room-panel">
        <div class="main">
            <div class="content w-1200" id="roomPanel">
                <Spin size="large" fix v-if="spinShow"></Spin>
                
                <div class="notice-wrapper" v-if="indexData.sysMessage" :style="{'display': noticeStyle}">
                    <span class="notice-l"><i class="icon icon-notice"></i>平台公告：</span>
                    <ul ref="sysMessageUl" :class="{'anim' : animate == true}">
                        <li v-for="(item, index) in indexData.sysMessage" :key="index" @click="sysMessageDetail(item.id)">{{item.content}}</li>
                    </ul>
                    <i class="icon icon-close" @click="closeNotice"></i>
                </div>

                <roomTitle @childMethod="upDateRoomData" :timeMessages="timeMessage" :cRoomData="cRoomData" :lotteryData="lotteryData" :newLotResult="newLotResult"></roomTitle>
                <div class="room-item">
                    <div v-if="zjFlag&&!showMiPai">
                        <div class="ivu-modal-mask absModal"></div>
                        <div class="ivu-modal-wrap vertical-center-modal absModal">
                            <img src="@/assets/images/reward_pic.png" class="zjImg">
                            <img src="@/assets/images/close5.png" class="zjCloseImg" @click="zjFlag=!zjFlag">
                            <div class="zjBox">
                                <p class="zjText">中奖<span>{{zjMoney}}</span>元宝</p>
                            </div>
                        </div>
                    </div>
                    <roomUserInfo></roomUserInfo>
                    <playMethods :timeMessages="timeMessage" :cRoomData="cRoomData" :BetmoneyList="BetmoneyList" :bindAbsClass="bindAbsClass" :newLotResult="newLotResult"></playMethods>
                    <chatRoom :allMessages="allMessage" :musicList="musicList" :bindAbsClass="bindAbsClass"></chatRoom>
                </div> 
            </div>
        </div>
        <Modal
            v-model="qczDlg"
            class-name=" qczModal"
            :scrollable="true"
            :mask-closable="false">
            <p>您的余额不足，请充值</p>
            <div slot="footer">   
                <Button type="primary" v-if="isUser"><router-link to="/topUpCenter/recharge" style="color: white">去充值</router-link></Button>
                <Button type="primary" @click="qczDlg=false" v-else>确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import roomTitle from "./roomTitle/roomTitle";
    import playMethods from "./playMethods/playMethods";
    import {initWebSocket,websocketsend,threadPoxi,websock} from "@/common/js/websocket";
    import chatRoom from "./chatRoom/chatRoom";
    import roomUserInfo from "./roomUserInfo/roomUserInfo";
    import {fetchJson} from "@/common/js/request";
    import router from "@/router";
    import _ from 'lodash';
    import { mapGetters, mapActions } from "vuex";    
    export default {
            data() {
                return {
                    allMessage:{},
                    timeMessage:{},//3001
                    cRoomData:[],//房间列表信息s
                    lotteryData:{},//开奖历史
                    newLotResult:{},//新的开奖结果
                    BetmoneyList:[5,10,50,100,500],
                    musicList:[],
                    spinShow:false,
                    zjFlag:false,
                    zjMoney: 0,//中奖元宝
                    bindAbsClass:false,
                    qczDlg: false,
                    isUser: true,
                    serTimer: {},
                    csCount: 0,
                    noticeStyle: 'block',
                    animate: false,
                    indexData: {}, //首页数据
		    csTimer: {},
                }
            },
            created() {},
            mounted() {
                this.getRoomData()
                this.windowScroll()
                this.getLottery()
                this.initWebSocket()
            },
            computed: {
                ...mapGetters(["accountData","showMiPai",'serTime', "lotRstData"])
            },
            activated() {
                if (this.indexData.sysMessage) {
                    this.setTime = setInterval(this.sysMessageScroll, 3000);
                }
            },
            methods: {
                ...mapActions(["SET_ACCOUNT_DATA"]),
                initWebSocket() {
                    fetchJson(this, "?m=api&c=workerman&a=getAllws", {}).then(result => {
                        var that = this
                        var address = []
                        if(!_.isEmpty(result)){
                            var j=0
                            for(var i in result){
                                address[j] = new WebSocket('wss://'+result[i])
                                j++
                            }
                            console.log('address', address)
                            for(var i in address){
                                address[i].addEventListener("open", function(event){
                                initWebSocket(event.currentTarget.url)
                                that.getData()
                                for(var j in address){
                                    address[j].close()
                        }
                                })
                            }
                            this.csTimer = setTimeout(()=>{
                                var flag = true
                                if(websock.readyState==1){
                                flag=false
                                }
                                if(flag){
                                    that.$Modal.warning({
                                        content: '连接房间超时，请重试',
                                        onOk:function(){
                                        that.$router.push({
                                            path: '/home'
                                        })
                                }
                                    })
                                    }
                            },5000*j)
                    }
                    })
                },
                goBottom: function(){
                    var scrollDiv = document.getElementById("chatcontent");
                    var chat = document.getElementById("chat");
                    setTimeout(function() {
                        scrollDiv.scrollTop = chat.scrollHeight;
                    }, 20);
                },
                serTimerFun: function(data){
                    clearInterval(this.serTimer)
                    var obj = data.serTime
                    this.serTimer = setInterval(()=>{
                        obj+=1
                        this.$store.commit('setSerTime',obj)
                    },1000)
                },
                getData: function(){
                    var that = this;
                    // if(that.csCount<3){
                    //     var csTimer = setTimeout(() => {
                    //         //超时重连3次
                    //         if(websock.readyState!=1){
                    //             that.csCount+=1
                    //             that.initWebSocket()
                    //         }
                    //     }, 3000)
                    // }else{
                    //     that.$Modal.warning({
                    //         content:'连接房间超时，请重试',
                    //         onOk:function(){
                    //             window.location.reload()
                    //         }
                    //     })
                    // }
                    websock.addEventListener("open", function(event){
                        that.spinShow=false
                        threadPoxi();
                        const agentData1 = {"commandid":"3002","uid":JSON.parse(localStorage.getItem("userData")).uid,"roomid":that.$route.query.id};
                        websocketsend(agentData1);
                        const agentData2 = {"commandid":"3017","uid":JSON.parse(localStorage.getItem("userData")).uid,"roomid":that.$route.query.id,"lottery_type":that.$route.query.lottery_type};
                        websocketsend(agentData2);
                    });
                    websock.addEventListener("message", function(event) {
                        
                        let data = JSON.parse(event.data);        
                        if(data.commandid!=3023){
                            console.log(data);             
                        }
                        if(data.commandid===3004||data.commandid===3007){
                            //聊天室信息
                            if(data.content.slice(1,3)=='追号'||data.content.slice(0,4)=='当前不在'||data.content.slice(0,4)=='投注失败'){                               
                                that.$Modal.remove();    
                                setTimeout(function(){
                                    that.$Modal.warning({
                                        content:data.content,
                                    });
                                },500);
                            }
                            //自己投注
                            if(JSON.parse(localStorage.getItem("userData")).uid==data.uid && data.commandid===3007){
                                that.$Message.success('投注成功');
                                that.goBottom()
                            }
                            if(data.commandid==3004&&data.has_not_money==1){
                                //余额不足
                                that.qczDlg=true
                                if(localStorage.getItem('isUser')){
                                    that.isUser=true
                                }else{
                                    that.isUser=false
                                }
                            }
                            that.allMessage=data;
                        }else if(data.commandid===3005){
                            //禁言提示
                            that.allMessage=data;
                        }else if(data.commandid===3001){
                            //倒计时
                            that.timeMessage=data;
                            that.allMessage=data;
                            that.serTimerFun(data)
                        }else if(data.commandid===3014){
                            //超时被踢
                            websock.close();
                            that.$Modal.remove();
                            if(!data.type){
                                setTimeout(function(){
                                    that.$Modal.warning({
                                        content:data.content,
                                        onOk:function(){
                                            // fetchJson(this, "?m=win&c=lobby&a=getLotteryRoomList",{}).then(res => {
                                            //     localStorage.removeItem("token")
                                            // });
                                            localStorage.removeItem("token")
                                            router.push({
                                                name:"Home",
                                                path:'/home',
                                            });;
                                        }
                                    });
                                },500);
                            }else{
                                setTimeout(function(){
                                    that.$Modal.warning({
                                        content:data.content,
                                        onOk:function(){
                                        router.push({
                                            name:"Home",
                                            path:'/home',
                                        });;
                                        }
                                    });
                                },500);
                            }
                            
                        }else if(data.commandid===3011){
                            //开奖结果
                            that.allMessage=data;
                            that.newLotResult=data;
                        }else if(data.commandid===3015){
                            //撤单成功
                            that.$Modal.remove();                            
                            that.allMessage=data;
                            that.$Message.info(data.content);                            
                        }else if(data.err){
                            that.$Modal.remove();                            
                            that.$Message.info(data.msg);
                        }else if(data.commandid===3019){
                            //追号成功
                            that.$Modal.remove();
                            that.allMessage=data;
                            that.$Message.success('追号成功');   
                            that.goBottom()                                                     
                        }else if(data.commandid==3022){
                            //追号撤单成功
                            that.$Modal.remove();
                            setTimeout(function(){
                                that.$Modal.success({
                                    content:data.content
                                });
                            },500);
                            that.allMessage=data;                            
                        }else if(data.commandid==3018){
                            //当期投注信息
                            that.allMessage=data;                            
                        }else if(data.commandid==3023){
                             //中奖飘窗
                            that.allMessage=data
                        }else if(data.commandid==3010){
                            //余额更新
                            var accountData = that.accountData
                            accountData.money_usable=data.money
                            that.SET_ACCOUNT_DATA({
                                Obj: accountData
                            })
                        }else if(data.commandid==3026){
                            //中奖
                            var accountData = that.accountData
                            accountData.money_usable=data.use_money
                            that.SET_ACCOUNT_DATA({
                                Obj: accountData
                            })
                            that.zjMoney=data.money
                            that.zjFlag=true
                        }else if(data.commandid==3025){
                            //再搏一次
                            that.allMessage=data                            
                        }else if(data.commandid==3061){
                            //本期排行
                            that.allMessage=data                            
                        }else if(data.commandid==3888){
                            //进房间提示
                            if(!_.isEmpty(data.greet)){
                                that.$Modal.info({
                                    title: '温馨提示',
                                    content: '<pre class="greet">'+data.greet+'</pre>'
                                })
                            }
                            that.allMessage=data                            

                        }
                    });
                    websock.addEventListener("close", function(event) {
                        console.log('closeeeeeeeeeeeeeeeeee')
                    });
                    websock.addEventListener("error", function(event) {
                        console.log(event, 'error')
                    });
                },
                getRoomData: function(){
                    if(this.$route.query.lottery_type==2){
                        //pk10
                        fetchJson(this, "?m=api&c=openAward&a=getTenData", {
                            type: this.$route.query.lottery_type
                            }).then(result => {
                            if (_.isEmpty(result)) {
                                return;
                            }
                            this.cRoomData = result.data;
                        });
                    }
                    fetchJson(this, "?m=win&c=lobby&a=getLotteryRoomList", {
                        //赔率信息接口
                        type: this.$route.query.lottery_type
                        }).then(result => {
                        if (_.isEmpty(result)) {
                            return;
                        }
                        this.cRoomData = result.data;
                        for(var i=0;i<this.cRoomData.p_room.length;i++){
                            if(this.$route.query.id==this.cRoomData.p_room[i].id&&this.cRoomData.p_room[i].passwd==""&&this.cRoomData.isAuthRoom!=0){
                                this.$Message.info('抱歉，您未开启当前房间权限！')
                                var that = this
                                setTimeout(function(){
                                    that.$router.push({
                                        path: '/home'
                                    })
                                },2000)
                                return false
                            }
                        }
                    });
                    fetchJson(this, "?m=api&c=openAward&a=getBetting",{}).then(result => {
                        if (_.isEmpty(result)) {
                            return;
                        }
                        this.BetmoneyList = result.list
                        this.musicList = result.music
                    });
                },
                getLottery:function(){
                    //获取开奖历史
                    let result = fetchJson(this,"?m=api&c=openAward&a=roomDataList",{
                        lottery_type:this.$route.query.lottery_type
                    }).then(result=>{
                        if(_.isEmpty(result)){
                            return;
                        }
                        this.lotteryData = result.list;
                    });
                },
                upDateRoomData:function(){//用于切换房间跟新数据
                    this.getData();
                    this.getRoomData();
                    this.getLottery();
                },
                windowScroll: function(){//固定投注和聊天框
                    var roomPanel = document.getElementById('roomPanel')
                    var chatcontent = document.getElementById('chatcontent')
                    var centermain = document.getElementById('centermain')
                    var flListPanel = document.getElementById('flListPanel')
                    var choosetoplayfooter = document.getElementById('choosetoplayfooter')
                    var zhPanel = document.getElementById('zhPanel')
                    if(roomPanel.clientHeight+128>window.pageYOffset+window.innerHeight){
                        let newHeight = window.innerHeight-chatcontent.getBoundingClientRect().top-54
                        let newHeight1 = window.innerHeight-centermain.getBoundingClientRect().top-167
                        chatcontent.style.height=newHeight+'px'
                        flListPanel.style.height=newHeight+'px'
                        // centermain.style.height=newHeight1+76+'px'
                        choosetoplayfooter.style.bottom=76+'px'
                        zhPanel.style.bottom=-newHeight1+'px'
                        this.bindAbsClass = true
                    }else{
                        this.bindAbsClass = false          
                    }
                    var that = this
                    window.onscroll = function(){
                        if(roomPanel.clientHeight+128>window.pageYOffset+window.innerHeight){
                            let newHeight = window.innerHeight-chatcontent.getBoundingClientRect().top-54
                            let newHeight1 = window.innerHeight-centermain.getBoundingClientRect().top-167
                            chatcontent.style.height=newHeight+'px'
                            flListPanel.style.height=newHeight+'px'
                            centermain.style.height=newHeight1+'px'
                            choosetoplayfooter.style.bottom=760-167-newHeight1+'px'

                            that.bindAbsClass = true
                        }else{
                            that.bindAbsClass = false          
                            choosetoplayfooter.style.bottom=0+'px'

                        }
                    }
                }
            },
            components: {roomTitle:roomTitle,playMethods:playMethods,chatRoom:chatRoom,roomUserInfo:roomUserInfo},
            watch: {
                indexData(obj) {
                    if (obj.sysMessage) {
                        this.setTime = setInterval(this.sysMessageScroll, 3000);
                    }
                },
                lotRstData: {
                    handler(newVal, oldVal){
                        if(!newVal.loadingFailed){
                        this.allMessage=JSON.parse(JSON.stringify(newVal))
                        }
                    }
                },
            },
            deactivated() {
                clearInterval(this.setTime)
            },
            beforeDestroy() {
                clearInterval(this.setTime)
                websock.close();
                clearInterval(this.csTimer)
            }

        }
</script>

<style scoped>
    .notice-wrapper {
        margin-top: -10px;
        margin-bottom: 10px;
        position: relative;
        padding: 0 36px 0 110px;
        height: 27px;
        color: #fff;
        overflow: hidden;
        background: rgba(255,255,255,0.3);
        border-radius: 3px;
    }
    .notice-wrapper .notice-l {
        position: absolute;
        left: 10px;
        top: 50%;
        margin-top: -10px;
    }
    .notice-wrapper .icon-notice {
        display: inline-block;
        margin-right: 5px;
        width: 20px;
        height: 20px;
        /* background: url('../../assets/images/room/icon-notice.png') no-repeat; */
    }
    .notice-wrapper .icon-close {
        cursor: pointer;
        position: absolute;
        right: 10px;
        top: 50%;
        margin-top: -8px;
        display: inline-block;
        width: 16px;
        height: 16px;
        /* background: url('../../assets/images/room/icon-close.png') no-repeat; */
    }
    .notice-wrapper .anim {
        transition: all .5s;
    }
    .notice-wrapper ul li {
        cursor: pointer;
        float: left;
        position: relative;
        width: 100%;
        height: 27px;
        line-height: 27px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .qczModal p{text-align: center;font-size: 14px;}
    .main {
        width: 100%;
        overflow: hidden;
        /* background-image: url(../../assets/images/bg.png); */
    }
    .main .content {
        margin-top: 20px;
        margin-bottom: 20px;
        border-radius: 5px;
        position: relative;
    }
    .room-item{display: flex;width: 100%;}
    .zjText{text-align: center;color: #FDCE32;font-size: 21px;font-weight: bold}
    .zjText span{color: #FFDC37;margin: 0 5px;}
    .zjClose{
        /* background: url('../../assets/images/viewdetail_button.png'); */
        background-size: 100% 100%;width: 108px;height: 39px;margin: 0 auto;line-height: 39px;color: #7E4300;font-weight: bold;font-size: 16px;text-align: center;cursor: pointer}
    .zjBox{position: relative;bottom: -110px}
    .zjImg{position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%)}
    .zjCloseImg{position: relative;bottom: 80px;left: 220px;cursor: pointer}
</style>
<style>
    .greet{white-space: pre-wrap; margin: 0;}
    .content .ivu-spin-fix{
        z-index: 99;
    }
    .absModal{z-index: 99 !important;position: absolute !important;}
    .absBox{position: fixed !important;bottom: 0px !important;}
    .choosetoplayfooter{background: white;height: 167px;position: absolute;bottom: 0px;width: 100%;}
    .leftBar{transform: translateY(100%);animation: bottomSlide 1s forwards;background-color: white;}
    @keyframes bottomSlide {
        0%{}
        100%{transform: translateY(0);}
    }
    @keyframes fadePanel {
        0%{opacity: 0}
        100%{opacity: 1}
    }
    .zhPanel{width: 322px;}
    .content .qrBetBtn{height: 38px !important;font-size: 16px;background-color: #2d8cf0 !important;border-color: #2d8cf0 !important}
    .content .qrBetBtn[disabled]:hover{color: #bbbec4 !important;}

    .clTitle{display: flex;justify-content: space-between;width: 100%;padding: 0px 11px;margin-top: 10px;}
    .clTitle span:first-child{font-size: 16px;}
    .pmPanel{width: 100%;}
    .pmTitle{margin: 8px 0px;}
    .betStatusTip{cursor: pointer;}
</style>



// WEBPACK FOOTER //
// src/components/room/room.vue